//
//  WBComposeView.swift
//  weibo
//
//  Created by yanghong on 15/12/16.
//  Copyright © 2015年 杨鸿. All rights reserved.
//

import UIKit
import pop
enum composeButtonAnimationType: Int {
    case Up = 0
    case Down = 1
}
class WBComposeView: UIView {
    
    var target: UIViewController?
    
    private lazy var buttons: [WBComposeButton] = [WBComposeButton]()
    //设置界面
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        var frame = self.frame
        
        frame.size = CGSizeMake(SCREENWIDTH, SCREENHEIGHT)
        
        self.frame = frame
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        //添加控件
        addSubview(bgImgView)
        addSubview(sloganImageView)
        //添加约束
        
        bgImgView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
            
        }
        
        sloganImageView.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self)
            
            make.top.equalTo(self).offset(100)
        }
        
        addChildButton()
        
    }
    
    // MARK -  添加按钮的方法
    
    private func addChildButton() {
        
        //button 的宽度
        //button 的高度
        let buttonWidth: CGFloat = 80
        let buttonHeight: CGFloat = 110
        //间距
        let buttonMargin: CGFloat = (SCREENWIDTH - 3 * buttonWidth) / 4
        
        let composeButtonInfos = getComposeButtonInfo()
        
        // print(composeButtonInfos)
        
        for (i, value) in composeButtonInfos.enumerate() {
            
            let button = WBComposeButton()
            //按钮的点击事件
            button.addTarget(self, action: "composeButtonClicked:", forControlEvents: .TouchUpInside)
            
            let icon = value.icon!
            
            let title = value.title!
            
            button.setImage(UIImage(named: icon), forState: .Normal)
            
            button.setTitle(title, forState: .Normal)
            
            button.size = CGSizeMake(buttonWidth, buttonHeight)
            
            // 计算出行列
            
            let col = i % 3
            let row = i / 3
            
            button.x = CGFloat(col + 1) * buttonMargin + CGFloat(col) * buttonWidth
            
            button.y = CGFloat(row) * buttonWidth + CGFloat(row) * buttonMargin + SCREENHEIGHT
            
            addSubview(button)
            
            buttons.append(button)
            
        }
        
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.35 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            self.removeFromSuperview()
        })
        
        //给button 设置动画 down 
        
        for (index, button) in buttons.enumerate() {
        
         popAnimation(button, type: .Down, index: index)
        
        }
        
    }
    // MARK -  按钮的点击事件
    
    @objc private func composeButtonClicked(button: UIButton) {
        
        // 给点击的button 设置放大的效果,其他的缩小
        
        // 遍历
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            for value in self.buttons {
                value.alpha = 0.3
                if value == button {
                
                    value.transform = CGAffineTransformMakeScale(1.6, 1.6)
                
                }else{
                
                    value.transform = CGAffineTransformMakeScale(0.4, 0.4)
                    
                }
       
            }

            }) { (_) -> Void in
                
                //跳转到相应的控制器
                
                let targetVc = WBComposeViewController()
                
                self.target?.presentViewController(WBNavigationController(rootViewController: targetVc), animated: true, completion: { () -> Void in
                    
                    self.removeFromSuperview()
                })
        
        }
    
    }
    
    // MARK - 获取按钮信息,字典转模型
    
    private func getComposeButtonInfo() -> [WBComposeButtonInfo] {
        
        let file = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)
        
        let composeButtonInfos = NSArray(contentsOfFile: file!)!
        
        var result = [WBComposeButtonInfo]()
        
        for value in composeButtonInfos {
            
            result.append(WBComposeButtonInfo(dict: value as! [String: AnyObject]))
            
        }
        return result
    }
    // MARK -  pop 执行动画
    /**
    pop 动画
    
    - parameter button:   需要执行动画的button
    - parameter type:     上升还是下降的动画
    - parameter duration: 执行时间
    */
    private func popAnimation(button: UIButton, type: composeButtonAnimationType,index: Int) {
        
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        //上升的动画
        if type == .Up {
            
            anim.toValue = NSValue(CGPoint: CGPointMake(button.center.x, button.center.y - 350))
            
        }else{
            anim.toValue = NSValue(CGPoint: CGPointMake(button.center.x, button.center.y + 350))
            
        }
        anim.springBounciness = 8
        anim.springSpeed = 10
        anim.beginTime = CACurrentMediaTime() + Double(index)*0.025
        button.pop_addAnimation(anim, forKey: nil)
    }
    // 外界调用这个方法显示界面
    func show(target: UIViewController?) {
        
        self.target = target
        
        target?.view.addSubview(self)
        
        //给每一个button添加设置好的动画
        
        for (index, button) in buttons.enumerate() {
        
        popAnimation(button, type: .Up, index: index)
        
        }
        
        
    }
    // MARK -  懒加载
    
    private lazy var bgImgView: UIImageView = UIImageView(image: UIImage.screenShoot().applyLightEffect())
    
    // 宣传语的图片
    private lazy var sloganImageView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
}
